#!/bin/env python3
import csv
import logging
import json
from datetime import datetime

log = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)

date_format = '%m/%d/%Y %H:%M:%S'

def parse_head(parser):
    head = next(parser)
    r = [{i: heading} for (i, heading) in enumerate(head)]
    log.info(r)
    return r

def parse_data(parser):
        num = 0
        for row in parser:
            num += 1
            record = {i: float(row[i]) for i in range(1, len(row))}
            record[0] = datetime.strptime(row[0], date_format)
            log.debug("record num=%s", num)
            log.debug("%s", record)
            yield record

def json_serial(obj):
    """JSON serializer for objects not serializable by default json code"""

    if isinstance(obj, datetime):
        return obj.isoformat()
    raise TypeError ("Type %s not serializable" % type(obj))


if __name__ == '__main__':
    log.info('start')
    with open('/d/SergeyR/Рус73_тестовые_данне.csv') as csvfile, \
         open('/tmp/data.json', 'w+') as json_file:
        parser = csv.reader(csvfile)
        head = parse_head(parser)
        json.dump({
            "head": head, 
            "data": list(parse_data(parser))
            }, json_file, indent=2, default=json_serial)
